#!/usr/bin/env node

const {EventEmitter} = require('events')
const log = console.log

class Queue extends EventEmitter {
    constructor() {
        super()
    }
    write(data) {
        this.#items.push(data)
        this.emit('dataAdded')
    }
    read() {
        return this.#items.shift()
    }
    isEmpty() {
        return this.#items.length === 0
    }

    #items = []
}

const queue = new Queue()

class Producer {
    constructor() {
        new Consumer()
    }
    create(data){
      log('+ prd create:', data)
      queue.write(data)
    }
}

class Consumer {
    constructor() {
        queue.on('dataAdded', () => {
            if (!queue.isEmpty()) {
                this.destroy()
            }
        })
    }
    destroy(){
      log('- csm destroy:', queue.read())
    }
}

function main() {
    const prd = new Producer()
    for(let i=0; i<5; i++) {
      prd.create(i)
    }
}
  
main()